package com.xs.bookspoststation.BookActivity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.xs.bookspoststation.R;
import com.xs.bookspoststation.adapter.BookAdapter;
import com.xs.bookspoststation.adapter.BookAdapter2;
import com.xs.bookspoststation.bean.Book;
import com.xs.bookspoststation.bean.Borrow;
import com.xs.bookspoststation.db.BookBean;
import com.xs.bookspoststation.db.DBHelperBook;
import com.xs.bookspoststation.db.DBHelperBorrow;

import java.util.ArrayList;
import java.util.List;

public class FindBookActivity extends AppCompatActivity {
    //定义对象
    private ListView listView_book;//与布局中的listView相配合
    Button quit;
    String username;
    String bookid,bookname,booknumber,bookauthor,bookshow;
    private BookBean bookBean;
    //定义一个数据库帮助类
    private DBHelperBorrow borrowHelp;
    private DBHelperBook bookHelp;
    private List<Book> bookList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_book);
        //绑定控件
        listView_book = (ListView)findViewById(R.id.listView_book);
        quit = (Button)findViewById(R.id.btn_book_back4);

        //先接受传来的username
        Intent intent=getIntent();
        username = intent.getStringExtra("username");

        //退出查看按键的响应
        quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    /**
     * 启动
     */
    @Override
    protected void onStart() {
        super.onStart();
        getData();
        BookAdapter2 myAdapter = new BookAdapter2(this, R.layout.booklist, bookList);
        listView_book.setAdapter(myAdapter);
        listView_book.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Book book = (Book) arg0.getItemAtPosition(arg2);
                bookid = book.getBookid();
                bookname = book.getBookname();
                booknumber = book.getBooknumber();
                bookauthor = book.getBookauthor();
                bookshow = book.getBookshow();
                //判断剩余书籍数量
                if(booknumber.equals("0")){
                    Toast.makeText(getApplicationContext(), "该图书余量:0，不可借阅！", Toast.LENGTH_LONG).show();
                }else{
                    boolean flage = false;
                    List<Borrow> borrows = null;
                    borrowHelp = new DBHelperBorrow(FindBookActivity.this,"borrow.db",null,1);
                    SQLiteDatabase db = borrowHelp.getReadableDatabase();
                    if(db.isOpen()){
                        Cursor cursor = db.query("borrowInfo", null, "username=?", new String[]{username}, null, null, null);//查询
                        borrows = new ArrayList<Borrow>();
                        while(cursor.moveToNext()){//一行一行遍历,并将一个一个book添加到books
                            Borrow borrow = new Borrow();
                            String BorrowUsername = cursor.getString(cursor.getColumnIndex("username"));//获取游标指定的id列的值
                            borrow.setUsername(BorrowUsername);
                            String BorrowBookId = cursor.getString(cursor.getColumnIndex("bookid"));
                            borrow.setBookid(BorrowBookId);
                            String BorrowBookName = cursor.getString(cursor.getColumnIndex("bookname"));
                            borrow.setBookname(BorrowBookName);
                            //用list的add方法将borrow添加到borrows
                            borrows.add(borrow);
                        }
                        cursor.close();//关闭cursor
                        db.close();
                    }
                    for(int i=0; i < borrows.size(); i++){
                        if((borrows.get(i).getBookid()).equals(bookid)){
                            flage=true;
                        }
                    }
                    if(flage){
                        Toast.makeText(getApplicationContext(), "您已借阅，不可重复借阅！", Toast.LENGTH_LONG).show();
                    }else{
                        //这里指定同一类型书，即图书编号一样的，每个用户只能借阅一本。
                        //先查看该用户是否已经借阅
                        AlertDialog.Builder builder=new AlertDialog.Builder(FindBookActivity.this);
                        builder.setTitle("是否借阅？");
                        builder.setPositiveButton("是的", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //这里对借的书籍数量进行操作
                                SQLiteDatabase db=bookHelp.getReadableDatabase();
                                Book tempbook = null;
                                //这里对借的书籍数量进行操作
                                if(db.isOpen()){
                                    tempbook = new Book();//
                                    Cursor cursor=db.query("bookInfo",null,"bookid=?",new String[]{bookid},null,null,null);
                                    while(cursor.moveToNext()){
                                        String tempBookId = cursor.getString(cursor.getColumnIndex("bookid"));
                                        String tempBookName = cursor.getString(cursor.getColumnIndex("bookname"));
                                        String tempBookNumber = cursor.getString(cursor.getColumnIndex("booknumber"));//获取游标指定的id列的值
                                        tempbook.setBookid(tempBookId);
                                        tempbook.setBookname(tempBookName);
                                        tempbook.setBooknumber(tempBookNumber);//借书，数量键1
                                        db.close();//关闭数据库
                                        break;
                                    }
                                }
                                //更新借阅后的图书信息
                                if(db.isOpen()){
                                    Book book1 = new Book();
                                    String bookid = book1.getBookid();
                                    String bookname = book1.getBookname();
                                    String booknumber = book1.getBooknumber();
                                    ContentValues c = new ContentValues();//类似于HashMap，但这个只能存储基本类型
                                    c.put("bookid", bookid);
                                    c.put("bookname", bookname);
                                    c.put("booknumber", booknumber);
                                    db.update("bookInfo", c, "bookid=?",new String[]{bookid});
                                    db.close();//关闭数据库
                                }
                                //增加借书信息
                                borrowHelp = new DBHelperBorrow(FindBookActivity.this,"borrow.db",null,1);
                                SQLiteDatabase db2 = borrowHelp.getWritableDatabase();//写的方式打开数据库
                                Borrow borrow =new Borrow(username, bookid, bookname);
                                if(db.isOpen()){
                                    String BorrowUsername = borrow.getUsername();
                                    String BorrowBookId = borrow.getBookid();
                                    String BorrowBookName = borrow.getBookname();
                                    //存储类，只能为String类型
                                    ContentValues values = new ContentValues();
                                    values.put("username",BorrowUsername);
                                    values.put("bookid",BorrowBookId);
                                    values.put("bookname",BorrowBookName);
                                    db.insert("borrowInfo",null,values);
                                    Log.v("添加借书信息操作", "借书 信息添加成功！");
                                    db.close();//关闭数据库
//                                    String BorrowUsername = borrow.getUsername();
//                                    String BorrowBookId = borrow.getBookid();
//                                    String BorrowBookName = borrow.getBookname();
//                                    db.execSQL("insert into borrowInfo (username,bookid,bookname) values (?,?,?)",new Object[]{BorrowUsername,BorrowBookId,BorrowBookName});
//                                    Log.v("添加借书信息操作", "借书 信息添加成功！");
//                                    db.close();
                                }
                                bookBean=new BookBean(FindBookActivity.this);
                                Toast.makeText(getApplicationContext(), "恭喜！借阅成功", Toast.LENGTH_LONG).show();
                                finish();
                            }});
                        builder.setNegativeButton("算了,不想看书", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                finish();
                            }});
                        builder.show();
                    }
                }
            }
        });
    }

    /**
     * 调用查询方法
     */
    private void getData() {
        bookHelp = new DBHelperBook(FindBookActivity.this,"book.db",null,1);
        bookBean = new BookBean(this);
        bookList = bookBean.findAll();
    }
}
